<template>
  <view class="voice-container">
    <view class="flex-ac">
      <!-- 播放按钮 -->
      <view class="voice-play-btn" @click="togglePlay">
        <u-icon
          v-if="!isPlaying"
          name="play-circle"
          color="#fff"
          size="24"
        ></u-icon>
        <u-icon v-else name="pause-circle" color="#fff" size="24"></u-icon>
      </view>
      <!-- 语音条 -->
      <view class="voice-bar" :style="{ width: progress + '%' }"></view>
    </view>
    <!-- 语音时长 -->
    <view class="voice-duration">{{ duration }}</view>
  </view>
</template>

<script>
export default {
  props: {
    audioSrc: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      audioContext: null,
      isPlaying: false,
      progress: 0, // 播放进度
      duration: "0:00", // 语音时长
      // audioSrc: 'https://example.com/your-audio-file.mp3' // 语音文件地址，需替换为实际地址
    };
  },
  created() {
    this.initAudio();
  },
  methods: {
    initAudio() {
      this.audioContext = uni.createInnerAudioContext();
      this.audioContext.src = this.$props.audioSrc;
      console.log(this.$props.audioSrc);
      this.audioContext.onPlay(() => {
        this.isPlaying = true;
        this.updateProgress();
      });
      this.audioContext.onPause(() => {
        this.isPlaying = false;
      });
      this.audioContext.onStop(() => {
        this.isPlaying = false;
        this.progress = 0;
      });
      this.audioContext.onEnded(() => {
        this.isPlaying = false;
        this.progress = 100;
      });
      this.audioContext.onCanplay(() => {
        this.duration = this.formatDuration(this.audioContext.duration);
      });
    },
    togglePlay() {
      if (this.isPlaying) {
        this.audioContext.pause();
      } else {
        this.audioContext.play();
      }
    },
    updateProgress() {
      const interval = setInterval(() => {
        if (!this.isPlaying) {
          clearInterval(interval);
          return;
        }
        this.progress =
          (this.audioContext.currentTime / this.audioContext.duration) * 100;
      }, 100);
    },
    formatDuration(seconds) {
      const minutes = Math.floor(seconds / 60);
      const secs = Math.floor(seconds % 60);
      return `${minutes}:${secs.toString().padStart(2, "0")}`;
    },
  },
};
</script>

<style lang="scss" scoped>
.voice-container {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background-color: #f60;
  height: 50rpx;
  width: 180rpx;
  padding: 10rpx 20rpx;
  border-radius: 45rpx;
  // margin: 10px;
}

.voice-bar {
  height: 10px;
  background-color: #fff;
  border-radius: 5px;
  transition: width 0.2s;
}

.voice-duration {
  margin-left: 20rpx;
  font-size: 24rpx;
  color: #fff;
}
</style>